<?php

define('TRANSLATION_DOMAIN', 'contraluz');
define('CL_GALLERY_TYPE_ACTIVE', true);

#############################################################
########################## SESSION ##########################
#############################################################

define('CL_URL_NUM_POSTS', 'cl_url_num_posts');

function cl_session_start(){
	if(!session_id()){
		session_start();
	}
	
	if(!array_key_exists(CL_URL_NUM_POSTS, $_SESSION)){
		$_SESSION[CL_URL_NUM_POSTS]= array();
	}
}
add_action( 'init', 'cl_session_start' );

#################################################################
########################## TRANSLATION ##########################
#################################################################

load_theme_textdomain(TRANSLATION_DOMAIN, TEMPLATEPATH.'/languages');

#################################################################
########################## THEME SETUP ##########################
#################################################################

/**
 * Sets up theme defaults and registers the various WordPress features that Contraluz supports.
 * @since Contraluz 1.0
 * @author Malhumorado
 */
function contraluz_setup() {	
	//add_theme_support( 'post-formats', array( 'aside', /*'chat',*/ 'gallery', 'image', 'link', 'quote', /*'status',*/ 'video', /*'audio'*/ ) );
	
	//add_theme_support( 'menus' );	
	
	add_theme_support( 'post-thumbnails' );		#enables Post thumbnails
	set_post_thumbnail_size( 150, 150 );		#set default Post Thumbnail dimensions
	if( function_exists( 'add_image_size' ) )
	{ 
		add_image_size( 'cl_gallery_small', 600, 600 );		
		add_image_size( 'cl_gallery_medium', 800, 800 );
		add_image_size( 'cl_gallery_big', 1024, 1024 );		
	}
	
	show_admin_bar(is_user_logged_in());
}
add_action( 'after_setup_theme', 'contraluz_setup' );

/**
 * You may need to flush the rewrite rules after changing this. 
 * You can do it manually by going to the Permalink Settings page and re-saving 
 * the rules -- you don't need to change them -- or by calling $wp_rewrite->flush_rules().
 * You should only flush the rules once after the taxonomy has been created, 
 * not every time the plugin/theme loads.
 */
function my_flush_rewrite_rules(){
	flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'my_flush_rewrite_rules' );

/**
 * Register theme menus
 */
function register_my_menus() {
	register_nav_menus( array(
		'main_menu'	=> __('Main Menu')
	));
}
//add_action( 'init', 'register_my_menus' );

#####################################################################
########################## LOGIN CUSTOMIZE ##########################
#####################################################################

function custom_login_css() { 
	echo '<link rel="stylesheet" type="text/css" href="'.get_bloginfo('template_directory').'/css/login.css" />'; 
}
add_action('login_head', 'custom_login_css');

function my_login_logo_url_title() {
    return get_bloginfo('name').' - '.get_bloginfo('description');
}
add_filter( 'login_headertitle', 'my_login_logo_url_title' );

function custom_login_header_url($url) {
	return get_bloginfo('url');
}
add_filter( 'login_headerurl', 'custom_login_header_url' );


function my_class_names($classes) {
    return array();
}
add_filter('body_class','my_class_names');

function get_current_logout( $logout_url ){
    $logout_url = add_query_arg('redirect_to', get_bloginfo('url'), $logout_url);
 	return $logout_url;
} 
add_filter('logout_url', 'get_current_logout');

###############################################################################
########################## SETUP GALLERY CUSTOM TYPE ##########################
###############################################################################

define('CL_GALLERY_POST_TYPE', 'cl_gallery');
define('CL_GALLERY_TAX_PLACES', 'gallery_places');
define('CL_GALLERY_LIGHTBOX_ACTIVE', TRUE);

/**
 * Create Gallery post type
 */
function register_gallery_type() {
	$labels = array(
	    'name' => __( 'Galleries', TRANSLATION_DOMAIN ),
	    'singular_name' => __( 'Gallery', TRANSLATION_DOMAIN ),
	    'add_new' => __( 'Add New', TRANSLATION_DOMAIN ),
	    'add_new_item' => __( 'Add New Gallery', TRANSLATION_DOMAIN ),
	    'edit_item' => __( 'Edit Gallery', TRANSLATION_DOMAIN ),
	    'new_item' => __( 'New Gallery', TRANSLATION_DOMAIN ),
	    'all_items' => __( 'All Galleries', TRANSLATION_DOMAIN ),
	    'view_item' => __( 'View Gallery', TRANSLATION_DOMAIN ),
	    'search_items' => __( 'Search Galleries', TRANSLATION_DOMAIN ),
	    'not_found' =>  __( 'No galleries found', TRANSLATION_DOMAIN ),
	    'not_found_in_trash' => __( 'No galleries found in Trash', TRANSLATION_DOMAIN ), 
	    'parent_item_colon' => '',
	    'menu_name' => __( 'Galleries', TRANSLATION_DOMAIN )
	);

	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true, 
		'show_in_menu' => true, 
		'query_var' => true,
		'rewrite' => array( 'slug' => 'gallery' ),
		'capability_type' => 'post',
		'has_archive' => true, 
		'hierarchical' => false,		
		'menu_position' => null,
		'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ), //, 'post-formats'
		'menu_position' => 4,
		'taxonomies' => array('category', 'post_tag')
	); 

	register_post_type( CL_GALLERY_POST_TYPE, $args ); 
}
add_action( 'init', 'register_gallery_type' );

/**
 * Add custom type to the loop in home page
 * @param unknown_type $query
 */
function cl_gallery_add_custom_type( $query ) {
	if ( is_home() && $query->is_main_query() )
		$query->set( 'post_type', array( 'post', CL_GALLERY_POST_TYPE ) );
	
	return $query; 
	
}
add_action( 'pre_get_posts', 'cl_gallery_add_custom_type' );

/**
 * Create taxonomies for Gallery type
 */
function register_gallery_taxonomies(){

	# Gallery places
	$labels = array(
		'name' => __( 'Places', TRANSLATION_DOMAIN ),
		'singular_name' => __( 'Place', TRANSLATION_DOMAIN ),
		'search_items' =>  __( 'Search Places', TRANSLATION_DOMAIN ),
		'all_items' => __( 'All Places', TRANSLATION_DOMAIN ),
		'parent_item' => __( 'Parent Place', TRANSLATION_DOMAIN ),
		'parent_item_colon' => __( 'Parent Place', TRANSLATION_DOMAIN ).':',
		'edit_item' => __( 'Edit Place', TRANSLATION_DOMAIN ), 
		'update_item' => __( 'Update Place', TRANSLATION_DOMAIN ),
		'add_new_item' => __( 'Add New Place', TRANSLATION_DOMAIN ),
		'new_item_name' => __( 'New Place Name', TRANSLATION_DOMAIN ),
		'menu_name' => __( 'Places', TRANSLATION_DOMAIN ),
	);	
	
	register_taxonomy(
		CL_GALLERY_TAX_PLACES, 
		array(
			CL_GALLERY_POST_TYPE
		), 
		array(
			'hierarchical' => true,
			'labels' => $labels,
			'show_ui' => true,
			'show_admin_column' => true,
			'query_var' => true,
			'rewrite' => array( 'slug' => 'places' )
		)
	);
}
add_action( 'init', 'register_gallery_taxonomies', 0 );  

/**
 * Customize/override gallery shortcode output
 * @param $attr
 */
function cl_gallery_shortcode($attr){
	$post = get_post();

	static $instance = 0;
	$instance++;

	if ( ! empty( $attr['ids'] ) ) {
		// 'ids' is explicitly ordered, unless you specify otherwise.
		if ( empty( $attr['orderby'] ) )
			$attr['orderby'] = 'post__in';
		$attr['include'] = $attr['ids'];
	}

	// Allow plugins/themes to override the default gallery template.
	$output = apply_filters('post_gallery', '', $attr);
	if ( $output != '' )
		return $output;

	// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
	if ( isset( $attr['orderby'] ) ) {
		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
		if ( !$attr['orderby'] )
			unset( $attr['orderby'] );
	}

	extract(shortcode_atts(array(
		'order'      => 'ASC',
		'orderby'    => 'menu_order ID',
		'id'         => $post->ID,
		'itemtag'    => 'li',
		'icontag'    => 'span',
		'captiontag' => 'label',
		'columns'    => 3,
		'size'       => 'thumbnail',
		'include'    => '',
		'exclude'    => ''
	), $attr));

	$id = intval($id);
	if ( 'RAND' == $order )
		$orderby = 'none';

	if ( !empty($include) ) {
		$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

		$attachments = array();
		foreach ( $_attachments as $key => $val ) {
			$attachments[$val->ID] = $_attachments[$key];
		}
	} elseif ( !empty($exclude) ) {
		$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
	} else {
		$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
	}
	
	//NO ATTACHMENTS
	if ( empty($attachments) )
		return '';

	//FEED
	if ( is_feed() ) {
		$output = "\n";
		foreach ( $attachments as $att_id => $attachment )
			$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
		return $output;
	}

	//GALLERY
	$size_class = sanitize_html_class( $size );
	$selector = CL_GALLERY_POST_TYPE."-{$instance}";

	$output= "<div class=\"clear\">";
	$output.= "<clgallery id='$selector' class='".CL_GALLERY_POST_TYPE."-list ".CL_GALLERY_POST_TYPE."-size-{$size_class}' position=\"{$instance}\">";
	
	$i=0;
	foreach ( $attachments as $id => $attachment ) {
		$i++;
		
		$title= trim($attachment->post_title)?wptexturize($attachment->post_title):null;				
		//$excerpt= trim($attachment->post_excerpt)?wptexturize($attachment->post_excerpt):null;		
		//$description= trim($attachment->post_content)?wptexturize($attachment->post_content):null;
		
		$output.="<clitem class=\"".CL_GALLERY_POST_TYPE."-item\" position=\"{$i}\">";
		
		# Normal display		
		//$output.= isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
				
		# Custom display (with lightbox integrated)
		
		list($img_thumb_src, $thumb_width, $thumb_height)= wp_get_attachment_image_src($attachment->ID, 'thumbnail');		
		list($img_display_src, $display_width, $display_height)= wp_get_attachment_image_src($attachment->ID, 'cl_gallery_big'); 		
		list($img_full_src, $full_width, $full_height)= wp_get_attachment_image_src($attachment->ID, 'full');

		$image_page_link = get_attachment_link($attachment->ID);
		
		$output.= '<a title="'.$title.'" href="'.(CL_GALLERY_LIGHTBOX_ACTIVE?$img_display_src:$image_page_link).'" '.(CL_GALLERY_LIGHTBOX_ACTIVE?'slide="yes" rel="lightbox['.$post->post_name.']"':'').' >';
		$output.= '<img src="'.$img_thumb_src.'" width="'.$thumb_width.'" height="'.$thumb_height.'" class="attachment-thumbnail" />';
		$output.= '</a>';		

		$output.= "</clitem>";
	}
	
	$output.= "</clgallery>";
	$output.= "<div class=\"clear\">";	

	return $output;
}
/**
 * Replace gallery shortcode renderize to custom one
 */
function register_cl_gallery(){
	remove_shortcode('gallery');
	add_shortcode('gallery', 'cl_gallery_shortcode');
}
add_action( 'init', 'register_cl_gallery' );

/**
 * Register meta boxes for Gallery type
 */
function register_gallery_meta_box(){
	# Gallery <timestamp>
	add_meta_box(
		'gallery_date_id',
		__( 'Taken date', TRANSLATION_DOMAIN ),
		'gallery_inner_custom_box',
		CL_GALLERY_POST_TYPE,
		'side',
		'high',
		array(
			'var' => 'timestamp'
		)
	);
}
/**
 * Render output for gallery custom boxes
 * @param $post
 * @param $metabox
 */
function gallery_inner_custom_box( $post, $metabox ){
	$var= $metabox['args']['var'];
	
	switch($var){
		# Gallery <timestamp>		
		case "timestamp":	
			
			wp_nonce_field('gallery_noncename_timestamp', 'gallery_save_timestamp');
			
			$gallery_timestamp= get_post_meta($post->ID, 'gallery_timestamp', true);
			if(!empty($gallery_timestamp)){			
				$g_day= date("j", $gallery_timestamp);
				$g_month= date("n", $gallery_timestamp);
				$g_year= date("Y", $gallery_timestamp);
			} else {
				$g_day= date("j");
				$g_month= date("n");
				$g_year= date("Y");
			}
			
			echo '<select name="gallery_day">'."\n";
			for($day=1; $day<=date("t"); $day++)
				echo '<option'.($day==$g_day?' selected="selected"':'').' value="'.$day.'">'.$day.'</option>'."\n";
			echo '</select>'."\n";
			
			echo '<select name="gallery_month">'."\n";
			for($month=1; $month<=12; $month++)
				echo '<option'.($month==$g_month?' selected="selected"':'').' value="'.$month.'">'.$month.'</option>'."\n";
			echo '</select>'."\n";
			
			echo '<select name="gallery_year">'."\n";
			for($year=1901; $year<=date("Y"); $year++)
				echo '<option'.($year==$g_year?' selected="selected"':'').' value="'.$year.'">'.$year.'</option>'."\n";
			echo '</select>'."\n";
			
			echo "&nbsp;<small>(dd/mm/yyyy)</small>"."\n";
			break;
	}	
}
add_action( 'add_meta_boxes', 'register_gallery_meta_box');

/**
 * Save gallery post data 
 * @param $post_id
 */
function gallery_save_postdata( $post_id ) {
	
	#Verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
		return;

	#Verify this came from the our screen and with proper authorization, because save_post can be triggered at other times	
	if ( !wp_verify_nonce( $_POST['gallery_save_timestamp'], 'gallery_noncename_timestamp' ) )
		return;
	  
	#Check permissions
	if ( 'clgallery' == $_POST['post_type'] ){
		if ( !current_user_can( 'edit_post', $post_id ) )
			return;
	}

	// OK, we're authenticated: we need to find and save the data

	# Gallery <timestamp>
	$day= $_POST['gallery_day'];
	$month= $_POST['gallery_month'];
	$year= $_POST['gallery_year'];    
	
	$gallery_timestamp= mktime(0, 0, 0, $month, $day, $year);
	
	if(!add_post_meta($post_id, 'gallery_timestamp', $gallery_timestamp, true)){
		update_post_meta($post_id, 'gallery_timestamp', $gallery_timestamp);  	  	
	}
}
add_action( 'save_post', 'gallery_save_postdata' );

/**
 * Get the places where gallery pictures where taken (use it in the loop)
 */
function cl_get_the_gallery_places(){
	$list= cl_get_taxonomies_hierachy(CL_GALLERY_TAX_PLACES);
	return $list;
}

/**
 * Get the date the gallery pictures where taken (use it in the loop)
 */
function cl_get_the_gallery_date(){
	$timestamp= get_post_meta(get_the_ID(), 'gallery_timestamp',true);
	return cl_timestamp_to_date(get_option('date_format'), $timestamp);	
}

/**
 * Get gallery thumbnail (use it in the loop)
 */
function cl_get_the_gallery_thumbnail($size='thumbnail'){
	return cl_get_the_post_thumbnail($size);
}

function cl_get_the_gallery_images_count2(){
	$id= get_the_ID();
	$total_attachments = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' && ID=$id");
	return $total_attachments;
}

function cl_get_the_gallery_images_count() {
	$id= get_the_ID();
    $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image'));
    if(!empty($attachments))
    	return count($attachments);
    return 0;
}

function cl_the_gallery_info(){
	cl_template('clgallery-info');
}

function is_cl_gallery_archive(){
	return is_post_type_archive(CL_GALLERY_POST_TYPE);	
}

function is_cl_gallery_places_archive(){
	return is_archive() && is_tax(CL_GALLERY_TAX_PLACES);
}

###################################################################
########################## GENERAL POSTS ##########################
###################################################################

function cl_post_is_preview(){
	global $more;
	return ($more!==1);
}

function cl_get_the_post_thumbnail($size='thumbnail'){
	$post_img= get_the_post_thumbnail(get_the_ID(), $size, array(
		'class' => 'post_thumbnail',
		//'title' => get_the_title(),
		'alt' => get_the_title()
	));
	return $post_img;
}

function cl_get_the_published_date($text_before=false){
	if($text_before)
		$date= sprintf( __( 'Published on %s', TRANSLATION_DOMAIN ), get_the_date(get_option('date_format')) );
	else
		$date= get_the_date(get_option('date_format'));
	
	return $date;		
}

function cl_get_the_modified_date($text_before=false){
	$p_date= get_the_date(get_option('date_format'));
	$p_time= get_the_date(get_option('time_format'));
	$m_date= get_the_modified_time(get_option('date_format'));
	$m_time= get_the_modified_time(get_option('time_format'));
	
	if($text_before){
		if($m_date!=$p_date || $m_time!=$p_time)
			$date= sprintf( __('Updated on %s at %s', TRANSLATION_DOMAIN), $m_date, $m_time );
		else 
			$date= sprintf( __('Published on %s at %s', TRANSLATION_DOMAIN), $m_date, $m_time);
	}
	else{
		$date= sprintf(__('%s at %s', TRANSLATION_DOMAIN), $m_date, $m_time);
	}
		
	return $date;	
}

function cl_count_posts(){
    global $wp_query;
    return sizeof( $wp_query->posts );    
}

function cl_timestamp_to_date($format, $timestamp){
	return mysql2date($format, date("Y-m-d H:i:s",$timestamp), true);
}

################################################################
########################## BREADCRUMB ##########################
################################################################

/**
 * Print a breadcrumb for current item;
 * @param $class String A comma-separated classes list
 * @param $echo Boolean Print output, default true
 */
function cl_breadcrumbs($class='breadcrumbs', $echo=true) {
	$breadcrumbs= array();
	
	# Retrieve bread crumbs
	if ( !is_home() && !is_front_page() || is_paged() ) {		
	
		# Attachment #
		if( is_attachment() ) {
								
			# PARENT POST TYPE #
			$post= get_post();
			$parent= get_post($post->post_parent);			
			$parent_type= get_post_type_object($parent->post_type);
			
			if($parent_type->name=='post')
				$url= get_bloginfo('url');
			else
				$url= get_post_type_archive_link($parent_type->name);

	    	$breadcrumbs[]= array(
				'title' => get_post_type_object($parent->post_type)->label,
				'link' => $url
	    	);						
			
			# PARENT POST #
	    	$breadcrumbs[]= array(
				'title' => get_the_title($parent->ID),
				'link' => get_permalink($parent->ID)
	    	);	    	
			
	    	# THIS #
	    	$breadcrumbs[]= array(
				'title' => get_the_title(),
				'link' => get_permalink()	    	
	    	);
		} 
		
		# Category #
		elseif( is_category() ){			
			$category= array_shift(get_the_category());		
			
	    	# CATEGORIES LABEL
	    	$breadcrumbs[]= array(
				'title' => __('Categories', TRANSLATION_DOMAIN)
	    	);	    	
	    	
	    	#THIS CATEGORY
	    	$breadcrumbs[]= array(
				'title' => $category->name,
				'link' => get_category_link($category->term_id)    	
	    	);				
	    		 
	    } elseif ( is_day() ) {
	    	
	    	pre('ES DIA');
	 
	    } elseif ( is_month() ) {
	    	
	    	pre('ES MES');
	 
	    } elseif ( is_year() ) {
	    	
	    	pre('ES AÑO');
	 
	    } 
	    
	    # Single #
	    elseif ( is_single() ) {

			# PARENT POST TYPE #
			$post= get_post();
			$parent= get_post($post->post_parent);			
			$parent_type= get_post_type_object($parent->post_type);
			
			if($parent_type->name=='post')
				$url= get_bloginfo('url');
			else
				$url= get_post_type_archive_link($parent_type->name);

	    	$breadcrumbs[]= array(
				'title' => get_post_type_object($parent->post_type)->label,
				'link' => $url
	    	);
	    	
	    	#THIS ELEMENT
	    	$breadcrumbs[]= array(
				'title' => get_the_title(),
				'link' => get_permalink()    	
	    	);		    	
	 
	    } elseif ( is_page() && !$post->post_parent ) {
	 
	    	pre('SIN PADRE');
	    	
	    } elseif ( is_page() && $post->post_parent ) {
	 		
	    	pre('CON PADRE');
	    } 
	    
	    # Search #
	    elseif ( is_search() ) {
	    	
	    	# Search #
			$breadcrumbs[]= array(
				'title' => __('Search results', TRANSLATION_DOMAIN),
				'link' => "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
	    	);	    	
	    	
	    	# SEARCHED ELEMENT
	    	$breadcrumbs[]= array(
				'title' => $_GET['s']
	    	);	 
	    	
	    	# NUM RESULTS
        	$breadcrumbs[]= array(
        		'title' => sprintf(__('%d results', TRANSLATION_DOMAIN), cl_count_posts())
	    	);
	    } 
	    
	    # Tag #
	    elseif ( is_tag() ) {

	    	# TAGS LABEL
	    	$breadcrumbs[]= array(
				'title' => __('Tags', TRANSLATION_DOMAIN)
	    	);	    	
	    	
	    	#THIS TAG
	    	$breadcrumbs[]= array(
				'title' => single_tag_title(null, false),
				'link' => get_tag_link(get_query_var('tag_id'))    	
	    	);	 		
	    } elseif ( is_author() ) {
	    	
	    	pre('ES AUTOR');
	 
	    } 
	    
	    # 404 not found #
	    elseif ( is_404() ) {
	    		    	
        	$breadcrumbs[]= array(
				'title' => __('Not Found', TRANSLATION_DOMAIN)
	    	);

	    } 
	    
	    # cl_gallery archive #
	    elseif(is_cl_gallery_archive()){
			
	    	# CUSTOM TYPE
        	$breadcrumbs[]= array(
				'title' => get_post_type_object(CL_GALLERY_POST_TYPE)->label,
        		'link' => get_post_type_archive_link(CL_GALLERY_POST_TYPE)
	    	);			
	    }
		
	    # cl_gallery places archive #
	    elseif(is_cl_gallery_places_archive()){
	    	$taxonomie= get_taxonomy(CL_GALLERY_TAX_PLACES);
	    	
	    	# PLACES
    	    global $wp_query;
		    $term = $wp_query->get_queried_object();
		    
		    while($term){
	            $breadcrumbs[]= array(
					'title' => $term->name,
	            	'link' => get_term_link($term)
		    	);

    	    	if($term->parent==0) break;	    		    	
		    	$term= get_term($term->parent, CL_GALLERY_TAX_PLACES);	
		    } 
		    
			# PLACES LABEL
            $breadcrumbs[]= array(
				'title' => $taxonomie->label,
	    	);	

	    	$breadcrumbs= array_reverse($breadcrumbs);
	    }
	 
	    if ( get_query_var('paged') ) {      
	    	if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) 
	    		echo ' (';      echo __('Page', TRANSLATION_DOMAIN) . ' ' . get_query_var('paged').')';      
		}
		
	}
	else{
		//pre('noo!');
	}
	
	#Add root crumb
    if(!empty($breadcrumbs)){
    	array_unshift($breadcrumbs, array(
			'title' => get_bloginfo('name'),
			'link' => get_bloginfo('url')
		));
    }
    
	# Print breadcrumb
	if(!empty($breadcrumbs)){
		if($class == 'breadcrumbs'){
			$list_class= '';
			$item_class= '';
		}
		elseif(!empty($class)){
			$item_class= implode('-item ', array_map('trim', explode(', ', $class))).'-item';
		}		
		
		$output= '<ul class="breadcrumbs '.$list_class.'">';
		
		foreach($breadcrumbs as $breadcrumb){
			$output.='<li class="breadcrumbs-item '.$item_class.'">';

			if(!empty($breadcrumb['link']))
				$output.='<a href="'.$breadcrumb['link'].'">'.$breadcrumb['title'].'</a>';
			else
				$output.= $breadcrumb['title'];
			
			$output.='</li>';
		}
		
		$output.='</ul>';
	}
	
	if($echo)
		echo $output;
	else
		return $output;	
}

###############################################################
########################## LOAD MORE ##########################
###############################################################

function cl_current_url($query_string=false) {
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	
	if( !$query_string && !empty($_SERVER['QUERY_STRING']) ){
		list($pageURL, $query)= explode('?', $pageURL, 2);				
	}	
	
	return $pageURL;
}

function posts_link_attributes() {
    return 'class="box small cl_next"';
}
add_filter('next_posts_link_attributes', 'posts_link_attributes');
//add_filter('previous_posts_link_attributes', 'posts_link_attributes');


function cl_nav_get_page_num(){
	global $wp_query;
	return (get_query_var('paged')>1?get_query_var('paged'):1);	
}

function cl_nav_get_posts_per_page(){
	return get_option('posts_per_page');	
}

function cl_nav_get_page_num_posts(){
	global $wp_query;
	return $wp_query->post_count;	
}

function cl_nav_get_max_num_pages(){
	global $wp_query;
	return $wp_query->max_num_pages;	
}

/*
function cl_ajax_set_posts_to_load() {
	$num_posts_to_load= $_POST['num'];
	$url= $_POST['url'];
	
	$_SESSION[CL_NAV_OBJ]->set_posts_to_load($num_posts_to_load, $url);
	
	exit();
}
add_action('wp_ajax_set_posts_to_load', 'cl_ajax_set_posts_to_load');
add_action('wp_ajax_nopriv_set_posts_to_load', 'cl_ajax_set_posts_to_load');


function cl_ajax_get_posts_to_load() {	
	$url= $_POST['url'];
	$num_posts_to_load= $_SESSION[CL_NAV_OBJ]->get_posts_to_load($url);
	
	echo $num_posts_to_load;
	
	exit();
}
add_action('wp_ajax_get_posts_to_load', 'cl_ajax_get_posts_to_load');
add_action('wp_ajax_nopriv_get_posts_to_load', 'cl_ajax_get_posts_to_load');
*/


function cl_number_posts_to_load($query){
	if ( !is_admin() && !is_search() && $query->is_main_query() ){
		$page= cl_nav_get_page_num();
		
		if($page>1){
			//Set num posts for current url
			$referer= $_POST['referer'];
			$_SESSION[CL_URL_NUM_POSTS][$referer]= $page * cl_nav_get_posts_per_page();			
		}
		elseif($page==1){
			//Get num posts for current url
			$num_posts_to_load= $_SESSION[CL_URL_NUM_POSTS][cl_current_url()];
			
			if(empty($num_posts_to_load)){
				$num_posts_to_load= 1 * cl_nav_get_posts_per_page();
				$_SESSION[CL_URL_NUM_POSTS][cl_current_url()]= $num_posts_to_load;
				//$query->set( 'paged', ($num_posts_to_load / cl_nav_get_posts_per_page()) );				
			}		
			
			$query->set( 'showposts', $num_posts_to_load );
		}
				
	}	
	
	return $query;
}
add_action('pre_get_posts', 'cl_number_posts_to_load');


###########################################################
########################## OTHER ##########################
###########################################################

/**
 * Print WP query posts
 */
function cl_the_loop(){
	cl_template('theloop');
}

/**
 * Get theme root
 */
function cl_get_theme_root(){
	return get_template_directory().DIRECTORY_SEPARATOR;
}
/**
 * Get theme templates path
 */
function cl_get_templates_root(){
	return cl_get_theme_root().'templates'.DIRECTORY_SEPARATOR;
}

/**
 * Include theme $template. If $template does not exist, warning will be output
 * @param $template
 * @param $more_text
 */
function cl_template($template, $more_text=null){
	if(empty($more_text))
		$more_text= '['.__('Read more...', TRANSLATION_DOMAIN).']';
	$filename= cl_get_templates_root()."template-{$template}-inc.php";
	
	if(file_exists($filename))
		include($filename);
	else
		cl_warning("Template '".basename($filename)."' not found!");
		
}

///** 
// * List terms in a given taxonomy using wp_list_categories
// * @param $taxonomy
// */
//function cl_get_taxonomies_hierachy($taxonomy, $list_class=null){
//	//list terms in a given taxonomy using wp_list_categories (also useful as a widget if using a PHP Code plugin)
//	$args_tax = array(
//		'taxonomy'     => $taxonomy,
//		'orderby'      => 'name',
//		'show_count'   => false,
//		'pad_counts'   => false,
//		'hierarchical' => true,
//		'title_li'     => '',
//		'echo' 		   => false
//	);
//	
//	if(empty($list_class))
//		$list_class= $taxonomy;
//	
//	$places= '<ul class="'.$list_class.'">'.wp_list_categories($args_tax).'</ul>';
//	
//	return $places;
//}

/** 
 * List terms in a given taxonomy using wp_list_categories
 * @param $taxonomy
 */
function cl_get_taxonomies_hierachy($taxonomy, $list_class=null){
	
	$terms = get_the_terms( $post->ID , $taxonomy );
	$result= array();
	
	if($terms){		
		foreach($terms as $term){
			$tree= cl_get_taxonomy_path($term->term_id, $taxonomy);
			if(count($tree) > count($result))
				$result= $tree;
		}
	}
	
	$result= array_reverse($result, true);
	
	if(empty($list_class))
		$list_class= $taxonomy;
	
	$output = '<ul class="'.$list_class.'">';
	foreach($result as $term_id => $term_name){
		//pre($term_id);
		$output.= '<li class="cat-item"><a href="'.get_term_link( (int)$term_id, $taxonomy).'">'.$term_name.'</a></li>';
	}
	$output.= '</ul>';
	
	return $output;
}

function cl_get_taxonomy_path($term_id, $taxonomy, $tree= null){
	//Create empty tree
	if(!is_array($tree)) $tree= array();
		
	//Get the term
	$term= get_term($term_id, $taxonomy);

	//Add term to tree
	$tree[$term_id]= $term->name; 		
		
	//Get parent
	if($term->parent!=0){
		return cl_get_taxonomy_path($term->parent, $taxonomy, $tree);		
	}
	
	//Return the tree
	return $tree;
}

function custom_taxonomy_walker($taxonomy, $parent = 0)
{
    $terms = get_terms($taxonomy, array('parent' => $parent, 'hide_empty' => false));
    //If there are terms, start displaying
    if(count($terms) > 0)
    {
        //Displaying as a list
        $out = "<ul>";
        //Cycle though the terms
        foreach ($terms as $term)
        {
            //Secret sauce.  Function calls itself to display child elements, if any
            $out .="<li>" . $term->name . custom_taxonomy_walker($taxonomy, $term->term_id) . "</li>"; 
        }
        $out .= "</ul>";    
        return $out;
    }
    return;
}

/**
 * Output warning
 * @param $message
 * @param $echo
 */
function cl_warning($message, $echo= true){
	$message= '<pre class="warning">'.$message.'</pre>';
	
	if($echo)
		echo $message;
	else 
		return $message;
}

/**
 * Inspect variable
 * @param var $value The value to inspect
 * @param boolean $stop Stop the execution after inspecting variable
 */
function pre($value, $stop=false){
	var_dump($value);
	if($stop) exit();
}
